package com.geline.uploadfile.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.extra.spring.SpringUtil;
import com.geline.uploadfile.enums.FileServerEnum;
import com.geline.uploadfile.enums.StatusEnum;
import com.geline.uploadfile.handler.UploadFileHandler;
import com.geline.uploadfile.pojo.JobUploadFile;
import com.geline.uploadfile.pojo.JobUploadFileProperties;
import com.geline.uploadfile.pojo.SelectFileBean;
import com.geline.uploadfile.service.BaseUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务：执行删除文件操作
 * @author: mengxin
 * @date: 2022/11/4 10:57
 */
@Slf4j
public class DeleteFileJob {

    private List<JobUploadFile> jobUploadFileList;
    private UploadFileHandler uploadFileHandler;
    private JdbcTemplate jdbcTemplate;

    public DeleteFileJob(JobUploadFileProperties properties, JdbcTemplate jdbcTemplate, UploadFileHandler uploadFileHandler){
        this.jobUploadFileList = properties.getList();
        this.jdbcTemplate = jdbcTemplate;
        this.uploadFileHandler = uploadFileHandler;
    }

    public void start(){
        for(JobUploadFile jobBean : this.jobUploadFileList){
            if(jobBean.isJobEnabled()){
                //每天03:10执行 删除7天前标识为[已删除]的文件 corn="0 10 3 1/1 * ?"
                CronUtil.schedule(jobBean.getJobCron(), new Task() {
                    @Override
                    public void execute() {
                        deleteFile(jobBean.getTable(), jobBean.getJobSelectSql());
                    }
                });
                log.info("启动定时任务[DeleteFileJob - {} - {}]!", jobBean.getTable(), jobBean.getJobCron());
            }
        }
        // 支持秒级别定时任务 CronUtil.setMatchSecond(true);
        if(!CronUtil.getScheduler().isStarted()){
            CronUtil.start();
        }
    }

    public int deleteFile(String table, String sql){
        long startTime = System.currentTimeMillis();
        int succNum = 0;
        StringBuilder objectNames = new StringBuilder();

        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        if(CollUtil.isNotEmpty(mapList)) {
            BaseUploadService baseUploadService = SpringUtil.getBean(BaseUploadService.class);
            List<SelectFileBean> beanList = mapList.stream().map(row -> BeanUtil.toBean(row, SelectFileBean.class)).collect(Collectors.toList());
            for (SelectFileBean bean : beanList){
                String sysFileServer = bean.getSysFileServer();
                FileServerEnum serverEnum = FileServerEnum.valueOf(sysFileServer);
                if(serverEnum == null){
                    log.warn("can not find sysFileServer = "+sysFileServer);
                    continue;
                }
                if(serverEnum.getIsEcs()){
                    boolean b = baseUploadService.deleteFileByRemote(bean.getBucket(), bean.getObjectName());
                    if(b){
                        ++succNum;
                        objectNames.append(bean.getObjectName()+",");
                        jdbcTemplate.execute(bean.getDeleteSql(table));
                    }
                }else{
                    boolean b = baseUploadService.deleteFileByLocal(bean.getBucket(), bean.getObjectName());
                    if(b){
                        ++succNum;
                        objectNames.append(bean.getObjectName()+",");
                        jdbcTemplate.execute(bean.getDeleteSql(table));
                    }
                }
            }
        }
        if(succNum > 0){
            log.debug(objectNames.toString());
            long endTime = System.currentTimeMillis();
            String message = String.format("删除无效文件[%s][%s个], 用时：%s秒", table, succNum, (endTime-startTime)/1000);
            uploadFileHandler.saveLog(StatusEnum.SUCCESS, "定时任务", message);
        }
        return succNum;
    }
}
